<?php
include 'rest_client.php';
//Automatically search trhough /pages and creates hyperlinks for each file
function CreateMenu(){
	foreach (glob("pages/[12345]_*.php") as $file) {
		$filename = substr($file, 8, -4); //Removes ".php" from filename. 
		$keys = array(" "); //Unwanted symbols. 
		$newkeys = array("-"); //Replacement symbols.
		$link = str_replace($keys, $newkeys, $filename);
		if ((($filename == "my profile") || ($filename == "friends"))) {
			if (!isset($_SESSION['username'])) {
				continue;
			}
		} 
		if($_GET['a']==$link){
			 $status = "btnselected"; 
		} else{
			$status = "btn";
		} 	
			echo '<li class="' . $status . '"><a href="?a=' . $link . '">' . $filename . '</a></li>';
	}
}
//Creates an array with the possible subpages
function CreateLinkArray(){
	foreach(glob("pages/*_*.php") as $filepath){
		$filename = substr($filepath, 8, -4);
		$keys = array(" ");
		$newkeys = array("-");
		$filename = str_replace($keys, $newkeys, $filename);
		$chk_array[$filename] = $filepath;
	}
	return $chk_array;
}

function fetchNewsFromDb($min, $max) {
	$query ="SELECT * FROM `News` ORDER BY date DESC LIMIT $min, $max";
	$result = mysql_query($query);
	return $result;
}

//Fetches news from database
function FetchNews($pagenr){
	$nrOfResultsPerPage = 10;
	$query = "SELECT COUNT(newsid) FROM News";
	$result = mysql_query($query);
	$nrOfPages = $result/$nrOfResultsPerPage;
	$min =  $pagenr * $nrOfResultsPerPage;
	$max = $min + $nrOfResultsPerPage;
	$result = fetchNewsFromDb($min, $max);
	while($row = mysql_fetch_array($result)) {
			$query = "SELECT username FROM Users WHERE userid='" . $row['userid'] . "'";
			$result2 = mysql_query($query);
			$user = mysql_fetch_assoc($result2);
		echo '<section class="newswrapper">
			<header class="newsheader">' . $row['topic'] . '</header>
			<section class="newssection">' . $row['news'] . '</section>
			<footer class="newsfooter">Posted by : ' . $user['username'] . '. ' . $row['date'] . '</footer>
			</section>';	
	}
}

//Write news to database
function writeNews($news, $username, $topic) {
	$query = "SELECT 'userid' FROM Users WHERE userid='$username'";
	$row = mysql_query($query);
	$query = "INSERT INTO News (news, date, userid, topic) VALUES('$news', NOW(), '" . $row['userid'] . "', '$topic')";
	mysql_query($query);
}

//Displays a graph using RGraph and data from our database
function displayGlobalTopAside($type, $nr, $id) {
	$client = new RestClient;
	//Retrieves artists/songs from database using our API
	$topartists = json_decode($client->get("/api/music/$type/top/$nr"), true);
	$test = 'artist';
	if($type == 'songs') {
		$test = 'title';
	} 
	echo "
       var data = [";
	   $string = ""; 
	   foreach($topartists as $artist) {
		   $string  = $string.$artist['count'].','; 
	   }
	   $string = substr($string,0,-1);
	   echo $string;
	   echo "];
        	var hbar = new RGraph.HBar('$id', data);
       		hbar.Set('chart.labels', [";
	   $string = ""; 
	   foreach($topartists as $artist) {
		   $string  = $string."'".$artist[$test]."',"; 
	   }
	   $string = substr($string,0,-1);
	   echo $string;
	   
	   //Some settings
	   echo "]);
        hbar.Set('chart.gutter.left', 135);
	hbar.Set('chart.gutter.top', 10);
	hbar.Set('chart.gutter.right', 50);
	hbar.Set('chart.xlabels', false);
        hbar.Set('chart.background.barcolor1', 'white');
        hbar.Set('chart.background.barcolor2', 'white');
        hbar.Set('chart.background.grid', false);
        hbar.Set('chart.colors', ['#CD0074']);
        
        // Now call the .Draw() method to draw the chart.
        hbar.Draw();
";
}

function displayUserTop($type, $nr, $id) {
	$client = new RestClient;
	$topartists = json_decode($client->get("/api/users/".$_SESSION['username']."/$type/top/$nr"), true);
	
	echo "
       var data = [";
	   $string = ""; 
	   foreach($topartists as $artist) {
		   $string  = $string.$artist['count'].','; 
	   }
	   $string = substr($string,0,-1);
	   echo $string;
	    echo "];
        var hbar = new RGraph.HBar('$id', data);
        
       hbar.Set('chart.labels', [";
	   $string = ""; 
	if($type == 'songs') {
		foreach($topartists as $artist) {
		   $string  = $string."'".$artist['artist']. " - ".$artist['title']."',"; 
	   }
	   $string = substr($string,0,-1);
	   echo $string;
	}  else { 
	   foreach($topartists as $artist) {
		   $string  = $string."'".$artist['artist']."',"; 
	  	}
	   $string = substr($string,0,-1);
	   echo $string;
	}   
	   echo "]);";
	  	if($type == 'songs') {
			echo "hbar.Set('chart.gutter.left', 250);";
		} else {
			echo "hbar.Set('chart.gutter.left', 135);";
		}
        
		echo "hbar.Set('chart.gutter.top', 10);
		hbar.Set('chart.gutter.right', 20);
		hbar.Set('chart.xlabels', false);
		hbar.Set('chart.labels.above', true);
        hbar.Set('chart.background.barcolor1', 'white');
        hbar.Set('chart.background.barcolor2', 'white');
        hbar.Set('chart.background.grid', false);
        hbar.Set('chart.colors', ['#CD0074']);
        
        // Now call the .Draw() method to draw the chart.
		hbar.Draw();";
}

function displayGlobalTop($type, $nr, $id) {
	$client = new RestClient;
	$topartists = json_decode($client->get("/api/music/$type/top/$nr"), true);

	echo "
       var data = [";
	   $string = ""; 
	   foreach($topartists as $artist) {
		   $string  = $string.$artist['count'].','; 
	   }
	   $string = substr($string,0,-1);
	   echo $string;
	   echo "];
        	var hbar = new RGraph.HBar('$id', data);
       		hbar.Set('chart.labels', [";
	   $string = ""; 
	if($type == 'songs') {
		foreach($topartists as $artist) {
		   $string  = $string."'".$artist['artist']. " - ".$artist['title']."',"; 
	   }
	   $string = substr($string,0,-1);
	   echo $string;
	}  else { 
	   foreach($topartists as $artist) {
		   $string  = $string."'".$artist['artist']."',"; 
	  	}
	   $string = substr($string,0,-1);
	   echo $string;
	}   
	   echo "]);";
	  	if($type == 'songs') {
			echo "hbar.Set('chart.gutter.left', 250);";
		} else {
			echo "hbar.Set('chart.gutter.left', 135);";
		}
        
		echo "hbar.Set('chart.gutter.top', 10);
		hbar.Set('chart.gutter.right', 20);
		hbar.Set('chart.xlabels', false);
		hbar.Set('chart.labels.above', true);
        hbar.Set('chart.background.barcolor1', 'white');
        hbar.Set('chart.background.barcolor2', 'white');
        hbar.Set('chart.background.grid', false);
        hbar.Set('chart.colors', ['#CD0074']);
        
        // Now call the .Draw() method to draw the chart.
        hbar.Draw();
";
}
//Retrieves artist listen count from database.
function artistListenCount($artist) {
	$client = new RestClient;
	$topartists = json_decode($client->get("/api/music/artists/$artist"), true);
	return $topartists[1]['count'];
}
//Login function. Sets Sessions variables.
function DoLogin($username,$password){
	$isOkay = checkLogin($username, $password);
	if ($isOkay == false) {
		return false;
	} else {
		$_SESSION['username'] = $username;
		$_SESSION['admin'] = $isOkay-1;
		return true;
	}
}

//Returns an array with username, password, email, name and adminstatus
function getUser($username) {
	$query = "SELECT * FROM Users WHERE username='$username'";
	$result = mysql_query($query);
	if (mysql_num_rows($result) != 1) {
		return false;
	} else {
		$row = mysql_fetch_array($result);
		return $row;
	}	
}

function updateUser($userid, $username, $email, $admin) {
	$query = "SELECT * FROM Users WHERE userid='$userid'";
	$result = mysql_query($query);
	$row = mysql_fetch_array($result);
	if($username == null) {
		$username = $row['username'];
	}
	if($email == null) {
		$email = $row['email'];
	}
	if($admin == null) {
		$admin = $row['admin'];
	}
	$query = "UPDATE `Users` SET username='$username', email='$email', admin='$admin' WHERE userid='$userid'";
	mysql_query($query);	
}

function removeUser($userid) {
	$query = "DELETE FROM `Users` WHERE userid='$userid'";
	mysql_query($query);
}

function checkLogin($username, $password) {
	$query = "SELECT * FROM Users WHERE username='$username' AND password=MD5('$password')";
	$result = mysql_query($query);
	if (mysql_num_rows($result) != 1) {
		return false;
	} else {
		$row = mysql_fetch_array($result);
		return 1+$row['admin'];
	}	
}


?>
